#include "Semaphore.h"

using namespace util;

Semaphore::Semaphore(const int resource)
    : resource_(resource)
{
}

void Semaphore::acquire()
{
    std::unique_lock<std::mutex> lock(mtx_);
    cond_.wait(lock, [&]()->bool {return resource_ > 0; });

    resource_--;
}

void Semaphore::release()
{
    std::unique_lock<std::mutex> lock(mtx_);
    resource_++;

    if (resource_ > 1)
        cond_.notify_all();
    else
        cond_.notify_one();
}
